package com.tourlaid.mamagerment.ao.pc.impl

import com.github.pagehelper.Page
import com.github.pagehelper.PageHelper
import com.tourlaid.mamagerment.ao.pc.GoodsAo
import com.tourlaid.mamagerment.entity.Goods
import com.tourlaid.mamagerment.entity.ResponseData
import com.tourlaid.mamagerment.service.GoodsService
import com.tourlaid.mamagerment.service.StockInService
import com.tourlaid.mamagerment.util.DateUtil
import com.tourlaid.mamagerment.util.MoneyUtil
import com.tourlaid.mamagerment.vo.GoodsListVo
import com.tourlaid.mamagerment.vo.GoodsVo
import org.springframework.beans.BeanUtils
import org.springframework.stereotype.Service
import org.springframework.util.CollectionUtils
import java.util.*
import javax.annotation.Resource

/**
 * Created by xiaoyongge on 2017/7/21.
 */
@Service("goodsAo")
class GoodsAoImpl : GoodsAo {

    @Resource
    val goodsService: GoodsService? = null
    @Resource
    val stockInService: StockInService? = null

    override fun list(pageNo: Int, pageSize: Int): ResponseData<ArrayList<GoodsListVo>> {
        var voList = ArrayList<GoodsListVo>()
        var responseData = ResponseData(voList)
        PageHelper.startPage<Goods>(pageNo, pageSize, true)
        var page = goodsService!!.queryForList()!! as Page<Goods>
        responseData.totalCount = page.getTotal()
        val goodsList = page.getResult()
        if (!CollectionUtils.isEmpty(goodsList)) {
            val goodsIdList = goodsList.map { goods -> goods.id }
            var stockInList = stockInService!!.queryByGoodsIds(goodsIdList)
            for (goods in goodsList) {
                var sum = 0
                stockInList.filter { stockIn -> Objects.equals(stockIn.goodsId, goods.id) }
                        .map { stockIn -> stockIn.stock }.forEach {
                    sum += it!!.toInt()
                }
                var vo = GoodsListVo()
                BeanUtils.copyProperties(goods, vo)
                vo.createTime = DateUtil.getFormantDate(goods.createTime, DateUtil.DATA_FORMANT3)
                vo.stock = sum
                voList.add(vo)
            }
        }
        return responseData
    }

    override fun insert(goodsName: String?, controlNo: String?) {
        goodsService!!.insert(goodsName, controlNo)
    }

    override fun detail(goodsId: Long): GoodsVo {
        var vo = GoodsVo()
        var goods = goodsService!!.getById(goodsId)
        vo.id = goods.id
        vo.goodsName = goods.goodsName
        vo.controlNo = goods.controlNo
        vo.imageOne = goods.imageOne
        vo.imageTwo = goods.imageTwo
        vo.imageThree = goods.imageThree
        vo.price = MoneyUtil.convertToYuan(goods.price)
        return vo
    }

    override fun update(goodsId: Long?, goodsName: String?, controlNo: String?) {
        goodsService!!.update(goodsId, goodsName, controlNo)
    }

    override fun delete(goodsId: Long?) {
        goodsService!!.delete(goodsId)
    }

}